var gulp = require('gulp');
// 在 shell 中执行一个命令
var exec = require('child_process').exec;
//gulp.task('default', function(cb) {
//	action();
//	// 将你的默认的任务代码放在这
//	gulp.watch('./src/js/**/*.js', function(event) {
//		console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
//		action();
//	});
//});

function action() {
	console.log("开始生成文件..");
	exec("browserify -t browserify-css ./src/js/main.js > ./src/bundle.js", function(err) {
		if(err) {
			console.log(err)
		} else {
			//			console.log("复制样式文件到 dist/css ...")
			//			gulp.src("./src/css/**/*").pipe(gulp.dest("./dist/css"));
			//			gulp.src("./src/img/**/*").pipe(gulp.dest("./dist/img"));
			//			gulp.src("./src/view/**/*").pipe(gulp.dest("./dist"));
			//copyFileToIdea();
			console.log("复制完成。");
		}
	});
}

var rootPath = process.cwd();
gulp.task('copyfile', function(cb) {
	copyFileToIdea();
	console.log("首次复制完毕！")
	gulp.watch('./src/**/**', function(event) {
		console.log('File ' + event.path);
		copySingleToIdea(event.path);
	});
});

function copySingleToIdea(filepath) {
	console.log(filepath)
	filepath = filepath.replace(rootPath, "");
	filepath = filepath.replace(/\\/g, "/");
	console.log(filepath)
	if(/^\/src\/[a-zA-Z0-9]+.html$/.test(filepath)) {
		gulp.src("." + filepath).pipe(gulp.dest(destPath + "/templates"));
	} else {
		var tempPath = filepath.replace("/src", "");
		var tempa = tempPath.split("/");
		tempa.pop();
		tempPath = tempa.join("/")
		gulp.src("." + filepath).pipe(gulp.dest(destPath + "/static/" + tempPath));
		console.log(new Date() + "  文件复制完成");
	}
}
var destPath = "D:/work/git/sbgrouptool/src/main/resources";
//var destPath = "D:/work/IdeaProjects/sbgrouptool/src/main/resources";
function copyFileToIdea() {
	gulp.src("./src/*.html").pipe(gulp.dest(destPath + "/templates"));
	gulp.src("./src/css/**/*").pipe(gulp.dest(destPath + "/static/css"));
	gulp.src("./src/img/**/*").pipe(gulp.dest(destPath + "/static/img"));
	gulp.src("./src/js/**/*").pipe(gulp.dest(destPath + "/static/js"));
	gulp.src("./src/base/**/*").pipe(gulp.dest(destPath + "/static/base"));
	gulp.src("./src/widget/**/*").pipe(gulp.dest(destPath + "/static/widget"));
}